<?php

class RegresionLineal 
{
	
	private $x = array();
	private $y = array();
	private $a = 0.0;
	private $b = 0.0;
	private $sx = 0.0;
	private $eA = 0.0;
	private $eB = 0.0;
	public function getSumatoriaX($x)
	{
	  $sx = 0.0;
      for( $i = 0; $i < count($x); $i ++)
		{
			$sx = $sx + $x[$i];
		}
		
		return $sx;
		
	}
	
	public function calculaPendiente($x, $y){
		$sxy = 0.0;
		$sx = 0.0;
		$sy = 0.0;
		$sx2 = 0.0;
		
		for( $i = 0; $i < count($x); $i ++)
		{
			$xy = $x[$i] * $y[$i];
			
			$sxy = $sxy + $xy;
	
			$sx = $sx + $x[$i];
			
			$sy = $sy + $y[$i];
			
			$sx2 = $sx2 + ( $x[$i] * $x[$i] );
	
		}
		
		$a = ( (real)(count($x) * $sxy) - (real)($sx * $sy) ) / (real)( (count($x) * $sx2) - ( $sx * $sx ) );
		
		return $a;//valor de la pendiente
	}

	public function calculaOrdenada($x, $y, $a, $sx){

		$sy = 0.0;
		$sx = 0.0;
		
		for( $i = 0; $i < count($x); $i ++){
			
			$sx = $sx + $x[$i];
			$sy = $sy + $y[$i]; 
		}
		
		$b = ($sy - ( $a * $sx ) ) / (real)count($x);
		return $b;//valor de la coordenada

	}
	
	public function getArrayNewFunction($x,$a,$b)
	{
		$new_array = array();
	    for( $i = 0; $i < count($x); $i ++)
		{
			$new_array[$i] = $x[$i]*$a+$b;
	
		}
		return $new_array;
	}
	
	public function calculaCorrelacion($x, $y, $sx) {
	
		$dxp = 0.0;
		$dyp = 0.0;
		$xp  = 0.0;
		
		$sx2 = 0.0;
		$sy2 = 0.0;
		
		$sdxpdyp = 0.0;
		
		for( $i = 0; $i < count($x); $i ++){
			
			$dxp = $x[$i] - ( $sx/(real)count($x) );
			$dyp = $y[$i] - ( $sx/(real)count($y) );
			
			$sdxpdyp = $sdxpdyp + ($dxp * $dyp);
			
			$sx2 = $sx2 + ( $dxp * $dxp );
			$sy2 = $sy2 + ( $dyp * $dyp );
			
		}
		
		$r = $sdxpdyp / (real)( sqrt($sx2) * sqrt($sy2) );
		
		return $r;//factor de correlacion
	}
	
	public function errorA($x, $y, $a, $b) {
	
		$k = 0.0;
		$sxy = 0.0;
		
		$sx = 0.0;
		$sx2 = 0.0;
		
		for( $i = 0; $i < count($x); $i ++){
			
			$sxy = $sxy + ( $y[$i] - ( $a * $x[$i]) - $b ) * ( $y[$i] - ( $a * $x[$i]) - $b ) ;
			$k = sqrt( $sxy / (real)( count($x) - 2 ) );
			
			$sx = $sx + $x[$i];
			$sx2 = $sx2 + ( $x[$i] * $x[$i] );
			
		}
		
		$eA = ( sqrt(count($x)) * $k ) / (real)( sqrt(( (count($x) * $sx2) - ( $sx * $sx ) )) );
		
		return $eA;//error de la variable a
	}
	
	public function errorB($x, $eA) {
	
		$sx2 = 0.0;
		
		for( $i = 0; $i < count($x); $i ++){
			
			$sx2 = $sx2 + ( $x[$i] * $x[$i] );
			
		}
		
		$eB = $eA * sqrt( $sx2 / (real)(count($x)) );
		
		return $eB;//error de la variable b
	}
	
	public function getY($x=0,$a, $b)
	{
		return $a*$x+$b;
	}
	
	public function getX($y=0,$a, $b)
	{
		return (real)($y-$b)/(real)$a;
	}

	
}

?>